package com.iwithlong.filter.http;

import java.io.Closeable;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by liyd on 16/5/10.
 */
public class HttpHandlerFactory {

    public static final String DEFAULT_HANDLER = "_default_handler";
    public static final String FINE_HANDLER = "_fine_handler";

    private final static Map<String, HttpHandler> HANDLER_MAP = new HashMap<String, HttpHandler>();

    static {
        registerHttpHandler(DEFAULT_HANDLER, new HttpClientHandler());
        registerHttpHandler(FINE_HANDLER, new FineHttpClientHandler ());
    }

    /**
     * 注册http处理器
     *
     * @param type
     * @param httpHandler
     */
    public static void registerHttpHandler(String type, HttpHandler httpHandler) {
        HANDLER_MAP.put(type, httpHandler);
    }

    /**
     * 获取httpHandler
     *
     * @param type
     * @return
     */
    public static HttpHandler getHttpHandler(String type) {
        return getHttpHandler(type, true);
    }


    /**
     * 获取httpHandler
     *
     * @param type
     * @param nonUseDefault
     * @return
     */
    public static HttpHandler getHttpHandler(String type, boolean nonUseDefault) {
        HttpHandler httpHandler = HANDLER_MAP.get(type);
        if (httpHandler == null && nonUseDefault) {
            httpHandler = HANDLER_MAP.get(DEFAULT_HANDLER);
        }
        return httpHandler;
    }

    /**
     * 销毁httpHandler
     *
     * @param httpHandler
     */
    public void closeQuietly(HttpHandler httpHandler) {
        Iterator<Map.Entry<String, HttpHandler>> iterator = HANDLER_MAP.entrySet().iterator();
        while (iterator.hasNext()) {
            HttpHandler handler = iterator.next().getValue();
            if (handler.getClass().getName().equals(httpHandler.getClass().getName())) {
                iterator.remove();
                if (handler instanceof Closeable) {
                    try {
                        ((Closeable) handler).close();
                    } catch (IOException e) {
                        //ignore
                    }
                }
            }
        }
    }

}
